<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import { jeecgBootExQuebankPageUsingPost,jeecgBootExQueSaveUsingPost,jeecgBootExQueGetUsingGet,jeecgBootExQueUpdateUsingPost } from "@/genapi/exam";
import { useAsync } from "@/hooks/use-async";
import FileOtherUpload from "@/components/file-system/file-otherUpload.vue";
import { ref } from "vue";
import {
	getEnumOptionsField,
	COURSE_TYPE_OPTIONS,
	QUESTION_TYPE_OPTIONS,
} from "@/config/enum-options";
import { useUserStore } from "@/stores/user";

import CreateTrace from "./create-trace.vue";

const userStore = useUserStore();

import { injectState } from "../state";

defineOptions({ name: "DetailDialog" });

const img = import.meta.glob("./assets/*.png", {
	import: "default",
	eager: true,
});

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"create" | "write" | "read">();

const options = ref([]);

const getOptions = async () => {
	const res = await jeecgBootExQuebankPageUsingPost({
		data: {
			size: 999,
			current: 1,
		},
	});
	res.result?.records?.map((item) => {
		options.value.push({
			label: item.name,
			value: item.id,
		});
	});
};

onMounted(() => {
	// getOptions();
});

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};

const trigger = async (
	_type: "write" | "read" | "create",
	value = {} as any,
) => {
	type.value = _type;
    model.value = JSON.parse(JSON.stringify(value)) as any;
    if (type.value === 'write') {
         const res = await jeecgBootExQueGetUsingGet({
            params: {
            id:model.value.id
        }
        })
        model.value = res.result;
        tableData.value = res.result.options;
        tableData.value.forEach(item => {
            if (item.img.length > 0) { 
                item.img = [item.img];
            } else {
                item.img = [];
            }
        })
    }
   
	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});
const value = ref("");

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "write"||type.value === "create") {
		return model.value.id ? "编辑" : "新建";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
    });
    let list = tableData.value
    list.map((item) => {
        if (item.img.length > 0) {
            item.img = item.img[0];
        } else {
            item.img = '';
        }
        
    }); 
    if (type.value === 'create') {
        await jeecgBootExQueSaveUsingPost({
            data: {
                ...model.value,
                options: tableData.value
            },
        });
    } else if (type.value === 'write') {
        await jeecgBootExQueUpdateUsingPost({
            data: {
                ...model.value,
                options: tableData.value
            },
        });
     }
	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});
const selectOptions = ref([{ label: "员工", value: "1" }]);

function getCurrentDate(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, "0");
	const day = String(now.getDate()).padStart(2, "0");

	return `${year}-${month}-${day}`;
}

model.value.time = getCurrentDate();

const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false);
const InputRef = ref();

const handleClose = (tag: string) => {
	model.value.tags.splice(model.value.tags.indexOf(tag), 1);
};

const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value!.input!.focus();
	});
};

const handleInputConfirm = () => {
	if (!model.value.tags) {
		model.value.tags = [];
	}
	if (inputValue.value) {
		model.value.tags.push(inputValue.value);
	}
	inputVisible.value = false;
	inputValue.value = "";
};

const children: FormDescChild[] = [
	{
		label: "",
		// prop: "status",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 2,
		fontSize: "16px",
		fontWeight: 700,
		formItem: () => (
			<div style="font-weight: 700; text-align: left;">新建题目</div>
		),
		descItem: `新建题目`,
	},
	{
		label: "题目工种",
		prop: "category",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.category}
				options={COURSE_TYPE_OPTIONS}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () =>
			getEnumOptionsField(COURSE_TYPE_OPTIONS, "label", model.value.category) ??
			"-",
	},
	{
		label: "题目类型",
		prop: "queType",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 2 / 3,
		formItem: () => (
			<el-select-v2
				v-model={model.value.queType}
				options={QUESTION_TYPE_OPTIONS}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () =>
			getEnumOptionsField(
				QUESTION_TYPE_OPTIONS,
				"label",
				model.value.queType,
			) ?? "-",
	},
	{
		label: "标签",
		prop: "tags",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
			<div
				style="
				width: 100%;
				align-items: center;
				border: 1px solid #dcdfe6;
				padding: 2px;
			"
			>
				{model.value.tags?.map((item) => (
					<el-tag
						style="margin-right:5px;"
						key={item}
						closable
						onClose={() => handleClose(item)}
					>
						{item}
					</el-tag>
				))}
				{inputVisible.value ? (
					<el-input
						ref="InputRef"
						v-model={inputValue.value}
						style="width:80px"
						size="small"
						onKeyup={{
							enter: handleInputConfirm,
						}}
						onBlur={handleInputConfirm}
					/>
				) : (
					<el-button class="button-new-tag" size="small" onClick={showInput}>
						+ New Tag
					</el-button>
				)}
			</div>
		),
		descItem: () => `${model.value.tags ?? "-"}`,
	},
	{
		label: "归属题库",
		prop: "queBankId",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.queBankId}
				options={options}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () => `${model.value.queBankId ?? "-"}`,
	},
	{
		label: "题目内容",
		prop: "content",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
			<el-input v-model={model.value.content} placeholder="请输入" row="2" />
		),
		descItem: () => `${model.value.content ?? "-"}`,
	},
	{
		label: "题目图片",
		prop: "images",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
			<div style={{ marginTop: "10px", marginLeft: "15px" }}>
				<FileOtherUpload
					onClick={() => {
						userStore.imgType = "从业资格证";
					}}
				/>
				<div
					style={{
						whiteSpace: "normal",
						width: "150px",
						color: "rgba(0, 0, 0, 0.25)",
					}}
				>
					支持bmp,jpg,png,tif格式图片可添加多个图片
				</div>
			</div>
		),
		descItem: () => `${model.value.images ?? "-"}`,
	},
	// {
	// 	label: "题目内容",
	// 	prop: "location",
	// 	rule: [{ required: true, message: "请输入", trigger: "blur" }],
	// 	span: 2,
	// 	formItem: () => (
	// 		<el-input v-model={model.value.location} placeholder="请输入" row="2" />
	// 	),
	// 	descItem: () => `${model.value.location ?? "-"}`,
	// },
];

interface Option {
	key: number;
	label: string;
	initial: string;
}

const generateData = () => {
	const data: Option[] = [];
	const states = [
		"California",
		"Illinois",
		"Maryland",
		"Texas",
		"Florida",
		"Colorado",
		"Connecticut ",
	];
	const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
	states.forEach((city, index) => {
		data.push({
			label: city,
			key: index,
			initial: initials[index],
		});
	});
	return data;
};

const data = ref<Option[]>(generateData());
const value1 = ref([]);

const filterMethod = (query, item) => {
	return item.initial.toLowerCase().includes(query.toLowerCase());
};

const question = ref({
	jobType: "string",
	questionType: "string",
	tags: ["1"],
	questionBank: "string",
	content: "string",
	image: "string",
	options: [
		{
			isAnswer: true,
			image: "string",
			answerContent: "string",
			answerExplanation: "string",
		},
	],
});

const tableData = ref([
	{
		content: "",
		img: [],
		index: "A",
		isRight: false,
		resolve: "",
	},
]);

/** 鼠标移入cell */
const handleCellEnter = (row, column, cell, event) => {
	row.isEdit = true;
};

/** 鼠标移出cell */
const handleCellLeave = (row, column, cell, event) => {
	row.isEdit = false;
};

const addRow = () => {
	tableData.value.push({
		content: "",
		img: [],
		index: "",
		isRight: false,
		resolve: "",
	});
	addIndex();
};

const addIndex = () => {
	tableData.value.forEach((item, index) => {
		item.index = String.fromCharCode(65 + index);
	});
};

const removeRow = (scope) => {
	tableData.value.splice(scope.$index, 1);
	addIndex();
};
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:before-close="beforeClose"
		w="700px!"
	>
		<el-scrollbar style="height: 508px">
			<!-- <CreateTrace :question="question" v-if="type === 'create'"></CreateTrace> -->
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="children"
				:column="2"
			/>
			<el-button
				style="margin-bottom: 5px"
				size="small"
				type="primary"
				@click="addRow"
				>添加</el-button
			>
			<el-table
				:data="tableData"
				size="small"
				style="width: 100%"
				@cell-mouse-enter="handleCellEnter"
				@cell-mouse-leave="handleCellLeave"
				show-overflow-tooltip
			>
				<el-table-column prop="name" label="是否答案">
					<template #default="scope">
						<el-checkbox
							v-model="scope.row.isRight"
							size="large"
							style="margin-right: 5px"
						/>{{ scope.row.index }}
					</template>
				</el-table-column>
				<el-table-column prop="singleNum" label="选项图片" width="100">
					<template #default="scope">
						<FileUpload class="w-100%!" v-if="scope.row.isEdit" v-model="scope.row.img" :limit="1">
							<el-button type="primary" size="small">点击上传 </el-button>
						</FileUpload>
                        <img class="img" :src="scope.row.img[0]" ></img>
					</template>
				</el-table-column>
				<el-table-column prop="singleNum" label="答案内容" width="190">
					<template #default="scope">
						<el-input
							v-if="scope.row.isEdit"
							class="cellItem"
							size="small"
							v-model="scope.row.content"
							placeholder="请输入"
							clearable
						></el-input>
						<div v-else class="txt">{{ scope.row.content }}</div>
					</template>
				</el-table-column>
				<el-table-column prop="singleScore" label="答案解析" width="190">
					<template #default="scope">
						<el-input
							v-if="scope.row.isEdit"
							class="cellItem"
							size="small"
							v-model="scope.row.resolve"
							placeholder="请输入"
							clearable
						></el-input>
						<div v-else class="txt">{{ scope.row.resolve }}</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="80" v-if="tableData.length > 1">
					<template #default="scope">
						<el-button type="text" @click="removeRow(scope)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-scrollbar>
		<template v-if="type === 'write'||type === 'create'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
		<template v-else-if="type === 'read'" #footer>
			<el-button @click="dialogRef?.close()">拒绝</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>通过</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.trainingListBox {
	width: 100%;
	padding: 0px 30px;

	.listBoxTitle {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
	}
}
</style>
